import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:live_music/components/ui/tag.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/pages/search/search_real_page.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/sp_utils.dart';

class SearchIndexPage extends StatefulWidget {
  SearchIndexPage({Key key}) : super(key: key);

  @override
  _SearchIndexPageState createState() => _SearchIndexPageState();
}

class _SearchIndexPageState extends State<SearchIndexPage>
    with SingleTickerProviderStateMixin {
  FocusNode _focusNode;

  ///默认不展示控件

  bool _offstage = true;

  ///监听TextField内容变化
  final TextEditingController _textEditingController = TextEditingController();
  List<dynamic> seachHistoryList = [];
  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _textEditingController.addListener(() {
      var isVisible = _textEditingController.text.isNotEmpty;
      _updateDelIconVisible(isVisible);
    });
    getData();
  }

  getData() async {
    List<dynamic> _seachHistoryList =
        await SPUtil.getObject('seachHistoryList');
    setState(() {
      seachHistoryList = _seachHistoryList ?? [];
    });
  }

  _updateDelIconVisible(bool isVisible) {
    setState(() {
      _offstage = !isVisible;
    });
  }

  changeKeyword() {
    print("object");
    setState(() {
      _textEditingController.text = "";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorRes.themeBg,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: Colors.white,
        automaticallyImplyLeading: false,
        title: SizedBox(
          width: double.infinity,
          height: 35,
          child: Row(
            children: [
               GestureDetector(
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                  color: Colors.black,
                ),
                onTap: () {
                  Get.back();
                },
              ),
              SizedBox(
                width: 5,
              ),
              Expanded(
                flex: 1,
                child: Container(
                  height: double.infinity,
                  margin: const EdgeInsets.only(left: 10),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border.all(color: Colors.grey, width: 0.5),
                      borderRadius: BorderRadius.circular(20)),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 8,
                      ),
                      Image.asset(
                        "assets/images/common/search.webp",
                        width: 24,
                        height: 24,
                        color: Colors.grey,
                      ),
                      SizedBox(
                        width: 8,
                      ),
                      Expanded(
                        flex: 1,
                        child:
                         TextField(
                          controller: _textEditingController,
                          autofocus: true,
                          focusNode: _focusNode,
                          cursorColor: Colors.redAccent,
                          style: TextStyle(fontSize: 14, color: Colors.black),
                          decoration: InputDecoration(
                            contentPadding: const EdgeInsets.only(bottom: 15),
                            border: InputBorder.none,
                            hintText: "输入关键词",
                            filled: true,
                            fillColor: Colors.white,
                          ),
                          maxLines: 1,
                        ),
                      ),
                      SizedBox(
                        width: 8,
                      ),
                      Offstage(
                        offstage: _offstage,
                        child: GestureDetector(
                          onTap: () => {_textEditingController.clear()},
                          child: Image.asset(
                            'assets/images/icons/pubish_close_pic.png',
                            width: 16,
                            height: 16,
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 8,
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                  margin: EdgeInsets.only(left: 10),
                  height: 30,
                  width: 60,
                  alignment: Alignment.center,
                  child: ElevatedButton(
                      style: ButtonStyle(
                          shape: MaterialStateProperty.all(
                              RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(20))),
                          backgroundColor: MaterialStateProperty.all(
                            Colors.redAccent,
                          )),
                      onPressed: () {
                        if (_textEditingController.text != "") {
                          bool flat = false;
                          for (int i = 0; i < seachHistoryList.length; i++) {
                            if (seachHistoryList[i] ==
                                _textEditingController.text) {
                              seachHistoryList.removeAt(i);
                              seachHistoryList.insert(
                                  0, _textEditingController.text);
                              flat = true;
                              break;
                            }
                          }
                          if (!flat) {
                            seachHistoryList.insert(
                                0, _textEditingController.text);
                          }
                          setState(() {
                            seachHistoryList = seachHistoryList;
                            _focusNode.unfocus();
                          });
                          SPUtil.saveObject(
                              'seachHistoryList', seachHistoryList);
                          Get.to(SearchRealPage(
                              keyword: _textEditingController.text,
                              changeKeyword: changeKeyword));
                        }
                      },
                      child: const Center(
                        child: Text(
                          '搜索',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 14,
                              fontWeight: FontWeight.w500),
                        ),
                      ))),
            ],
          ),
        ),
        centerTitle: true,
      ),
      body: Container(
          padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
          alignment: Alignment.centerLeft,
          child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "历史记录",
                  style: TextStyle(color: Colors.black),
                ),
                InkWell(
                  child: Icon(
                    Icons.delete_forever,
                    color: Colors.grey,
                  ),
                  onTap: () {
                    SPUtil.remove('seachHistoryList');
                    setState(() {
                      seachHistoryList = [];
                    });
                  },
                )
              ],
            ),
            SizedBox(
              height: 8,
            ),
            Container(
                margin: const EdgeInsets.all(12),
                alignment: Alignment.centerLeft,
                child: Wrap(
                  spacing: 12,
                  runSpacing: 12,
                  children: seachHistoryList
                      .asMap()
                      .entries
                      .map(
                        (e) => InkWell(
                            onTap: () {
                              seachHistoryList.removeAt(e.key);
                              seachHistoryList.insert(0, e.value);
                              setState(() {
                                _textEditingController.text = e.value;
                                _focusNode.unfocus();
                                seachHistoryList = seachHistoryList;
                              });
                              Get.to(SearchRealPage(
                                  keyword: e.value,
                                  changeKeyword: changeKeyword));
                              SPUtil.saveObject(
                                  'seachHistoryList', seachHistoryList);
                            },
                            child: Container(
                                padding: const EdgeInsets.symmetric(
                                  vertical: 6,
                                  horizontal: 12,
                                ),
                                decoration: BoxDecoration(
                                  border: Border.all(
                                      color: Colors.grey[400], width: 0.5),
                                  borderRadius: BorderRadius.circular(15),
                                ),
                                child: Text(
                                  e.value,
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                  ),
                                ))),
                      )
                      .toList(),
                ))
          ])),
    );
  }
}
